﻿#pragma warning disable CS8632
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.IO;

namespace Unity.Logger.Providers
{
    [ProviderAlias("FileLogger")]
    public class FileLoggerProvider : ILoggerProvider
    {
        internal const string DefaultOptionName = "FileLogger.Default";

        AsyncStreamLineMessageWriter streamWriter;

        public FileLoggerProvider(string filePath, IOptionsMonitor<LogOptions> options)
            : this(filePath, DefaultOptionName, options)
        {
        }

        public FileLoggerProvider(string filePath, string? optionName, IOptionsMonitor<LogOptions> options)
        {
            var di = new FileInfo(filePath).Directory;
            if (!di!.Exists)
            {
                di.Create();
            }

            var opt = options.Get(optionName ?? DefaultOptionName);

            // useAsync:false, use sync(in thread) processor, don't use FileStream buffer(use buffer size = 1).
            var stream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 1, false);
            this.streamWriter = new AsyncStreamLineMessageWriter(stream, opt);
        }

        public ILogger CreateLogger(string categoryName)
        {
            return new AsyncProcessLog(categoryName, this.streamWriter);
        }

        public void Dispose()
        {
            this.streamWriter.DisposeAsync().AsTask().Wait();
        }
    }
}
